<template>
	<a-modal
		:visible="visible"
		width="1100px"
		title="添加销方开票信息"
		:bodyStyle="{padding: 0}"
		centered
		destroyOnClose
		:maskClosable="false"
		@cancel="cancel">
		<a-form ref="formRef" :rules="certRules" :model="modelRef" class="add-invoicing-info" style="height: 70vh" layout="vertical">
			<!-- <div class="flex1 auto-y"> -->
			<a-row :gutter="24" v-if="rejectionReason">
				<a-col :span="24">
					<div class="tip-info">
						<exclamation-circle-filled color="warning" />
						{{ rejectionReason }}
					</div>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item
						label="所属部门"
						name="departmentId"
						label-align="left"
						:rules="[{required: true, message: '请选择所属部门'}]"
						class="a-form-item">
						<a-tree-select
							v-model:value="modelRef.departmentId"
							show-search
							style="width: 100%"
							:dropdown-style="{maxHeight: '400px', overflow: 'auto'}"
							placeholder="请选择部门"
							allow-clear
							:tree-default-expanded-keys="treeExpandedKeys"
							:tree-data="treeData"
							:field-names="{
								children: 'childList',
								label: 'name',
								value: 'id'
							}"
							:disabled="props.detail?.departmentId ? true : false"
							treeNodeFilterProp="name"
							@select="select"></a-tree-select>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="不开票的费用科目:" htmlFor="label" :rules="[{required: true, message: '请选择不可开票费用科目'}]">
						<a-select
							v-model:value="modelRef.disabledFeeSubjectId"
							mode="multiple"
							style="width: 100%"
							:options="dict.notInvoiced"
							size="middle"
							:field-names="{label: 'name', value: 'id', options: 'metaList'}"
							placeholder="请选择(选择后的费用类型的账单明细将不在可开发票页面展示)"
							@blur="selectFee(-1)"
							@focus="autofocus(-1)"></a-select>
					</a-form-item>
				</a-col>
			</a-row>

			<a-typography-text strong>
				<blockquote class="fee-title">默认收款账号</blockquote>
			</a-typography-text>
			<a-row :gutter="24">
				<a-col :span="8">
					<a-form-item label="企业名称:" htmlFor="label" :rules="[{required: true, message: '请选择企业名称'}]">
						<a-select
							v-model:value="defaultFee.invOrgId"
							size="middle"
							style="width: 100%"
							:options="enterpriseList"
							:field-names="{label: 'name', value: 'id'}"
							placeholder="请选择企业"
							@change="changeEnterprise(defaultFee.invOrgId, -1, defaultFee)"
							@blur="selectEnterprise(defaultFee.invOrgId, -1)"
							@focus="enterpriseFocus(defaultFee.invOrgId)"></a-select>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="税号:" htmlFor="label" :rules="[{required: true, message: '请输入税号'}]">
						<a-input v-model:value="defaultFee.taxpayerNum" disabled placeholder="根据所选企业自动填充" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<!-- :rules="[{required: true, message: '请选择开票设备类型'}]" -->
					<a-form-item label="开票设备类型:" name="deviceType" htmlFor="label">
						<a-select
							mode="multiple"
							v-model:value="modelRef.deviceType"
							max-tag-count="responsive"
							style="width: 100%"
							:options="enterPriseData[enterpriseIndex]?.taxControlDeviceTypeList"
							:field-names="{label: 'name', value: 'id'}"
							placeholder="请选择开票设置类型"></a-select>
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="24">
				<a-col :span="8">
					<a-form-item label="开票人姓名:" htmlFor="label" :rules="[{required: true, message: '请输入开票人姓名'}]">
						<a-input v-model:value="defaultFee.drawerName" :maxlength="16" placeholder="请输入开票人姓名" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="复核人姓名:" htmlFor="label" :rules="[{required: true, message: '请输入复核人姓名'}]">
						<a-input v-model:value="defaultFee.reviewerName" :maxlength="16" placeholder="请输入复核人姓名" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="收款人姓名:" htmlFor="label" :rules="[{required: true, message: '请输入收款人姓名'}]">
						<a-input v-model:value="defaultFee.takerName" :maxlength="20" placeholder="请输入收款人姓名" />
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="8">
					<a-form-item label="地址:" htmlFor="label" :rules="[{required: true, message: '请输入地址'}]">
						<a-input v-model:value="defaultFee.sellerAddress" :maxlength="100" placeholder="请输入地址" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="电话:" htmlFor="label" :rules="[{required: true, message: '请输入电话'}]">
						<a-input v-model:value="defaultFee.sellerTel" :maxlength="20" placeholder="请输入电话" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="开户行:" htmlFor="label" :rules="[{required: true, message: '请输入开户行'}]">
						<a-input v-model:value="defaultFee.sellerBankName" :maxlength="100" placeholder="请输入开户行" />
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="8">
					<a-form-item label="银行卡号:" htmlFor="label" :rules="[{required: true, message: '请输入银行卡号'}]">
						<a-input v-model:value="defaultFee.sellerBankAccount" :maxlength="100" placeholder="请输入银行卡号" />
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col v-if="show(modelRef.deviceType)" :span="24">
					<!-- <a-form-item htmlFor="label">
						<template #label>
							<span v-color="{color: 'danger'}">*</span>
							金税盘/税控盘/税务 UKEY配置:
						</template> -->
					<a-typography-text strong>
						<blockquote style="margin-top: 0" class="fee-title">金税盘/税控盘/税务 UKEY配置:</blockquote>
					</a-typography-text>

					<a-row :gutter="24">
						<a-col :span="8">
							<a-form-item label="税盘号+终端号:" htmlFor="label" :rules="[{required: true, message: '请选择税盘号+终端号'}]">
								<a-select
									v-model:value="defaultFee.machineCodeId"
									size="middle"
									style="width: 100%"
									:options="extensionInfoList"
									:field-names="{label: 'name', value: 'id'}"
									placeholder="请先选择企业"
									@select="selectMachineCode(defaultFee.machineCodeId, -1)"></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="剩余发票数量:" htmlFor="label" :rules="[{required: true, message: ''}]">
								<a-input v-model:value="defaultFee.invoiceSurplusNum" disabled placeholder="根据所选企业自动填充" />
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<!-- :rules="[{required: true, message: ''}]" -->
							<a-form-item label="单张开票限额:" htmlFor="label">
								<a-input-number v-model:value="defaultFee.invoiceLimit" disabled placeholder="请输入单张开票限额" />
							</a-form-item>
						</a-col>
					</a-row>
					<!-- </a-form-item> -->
				</a-col>
				<a-col v-if="modelRef.deviceType?.includes(5)" :span="24">
					<!-- <a-form-item htmlFor="label">
						<template #label>
							<span v-color="{color: 'danger'}">*</span>
							全电发票配置:
						</template> -->
					<a-typography-text strong>
						<blockquote style="margin-top: 0" class="fee-title">全电发票配置 :</blockquote>
					</a-typography-text>
					<a-row :gutter="24">
						<a-col :span="8">
							<!-- 默认是 -->
							<a-form-item
								label="主体是否存在不动产租赁服务相关的税收分类编码 :"
								htmlFor="label"
								:rules="[{required: true, message: ''}]">
								<a-select
									v-model:value="modelRef.existImmovables"
									size="middle"
									style="width: 100%"
									:options="isCrossCity"
									:field-names="{label: 'name', value: 'id'}"></a-select>
							</a-form-item>
						</a-col>
						<a-col v-if="modelRef.existImmovables" :span="8">
							<a-form-item
								label="不动产所在地:"
								name="region"
								:rules="[{required: modelRef.existImmovables, message: '请输入不动产所在省市(县)区'}]">
								<a-input
									:minlength="4"
									:maxlength="50"
									v-model:value="modelRef.region"
									placeholder="请输入不动产所在省市(县)区" />
							</a-form-item>
						</a-col>
						<a-col v-if="modelRef.existImmovables" :span="8">
							<a-form-item
								label="不动产详细地址:"
								name="detailedAddress"
								:rules="[{required: modelRef.existImmovables, message: '请输入不动产所在详细地址'}]">
								<a-input :maxlength="100" v-model:value="modelRef.detailedAddress" placeholder="请输入不动产所在详细地址" />
							</a-form-item>
						</a-col>
						<a-col v-if="modelRef.existImmovables" :span="8">
							<a-form-item
								label="面积单位:"
								name="areaUnit"
								:rules="[{required: modelRef.existImmovables, message: '请选择面积单位'}]">
								<a-select
									v-model:value="modelRef.areaUnit"
									size="middle"
									style="width: 100%"
									:options="areaUnitList"
									:field-names="{label: 'name', value: 'id'}"
									placeholder="请选择面积单位"></a-select>
							</a-form-item>
						</a-col>
						<a-col v-if="modelRef.existImmovables" :span="8" style="line-height: 87px">
							<a-form-item
								label="是否跨地(市):"
								name="crossCitySign"
								:rules="[{required: modelRef.existImmovables, message: ''}]">
								<a-select
									v-model:value="modelRef.crossCitySign"
									size="middle"
									style="width: 100%"
									:options="isCrossCity"
									:field-names="{label: 'name', value: 'id'}"></a-select>
							</a-form-item>
							<!-- 默认否 -->
						</a-col>
						<a-col v-if="modelRef.existImmovables" :span="8">
							<a-form-item label="租赁起止日:" :rules="[{required: modelRef.existImmovables, message: ''}]">
								<a-range-picker
									:value="[modelRef.leaseBeginDate, modelRef.leaseEndDate]"
									:value-format="DATE_FORMAT.DATE"
									style="flex: 1"
									@change="dates => onDateChange(modelRef, dates)" />
							</a-form-item>
						</a-col>
						<a-col v-if="modelRef.existImmovables" :span="8">
							<a-form-item label="产权证书/不动产权号:" name="titleNo">
								<a-input :maxlength="40" v-model:value="modelRef.titleNo" placeholder="请输入产权证书/不动产权号" />
							</a-form-item>
						</a-col>
					</a-row>
					<!-- </a-form-item> -->
				</a-col>
			</a-row>

			<a-typography-text strong>
				<blockquote style="margin-top: 0" class="fee-title">
					特殊费用配置：
					<a-button type="link" @click="listPush"><plus-circle-outlined /></a-button>
				</blockquote>
			</a-typography-text>
			<div class="list-null" v-if="!otherExpenses.length">
				<a-empty :image="simpleImage" />
			</div>

			<template v-else>
				<div class="special-expenses-box" v-for="(item, index) in otherExpenses" :key="index">
					<div class="title">
						<div>特殊费用</div>
						<a-button type="link" @click="listDetele(index)"><close-outlined @chick="listDetele(index)" /></a-button>
					</div>
					<div class="form-main">
						<a-row :gutter="24">
							<a-col :span="12">
								<a-form-item label="费用科目:" htmlFor="label" :rules="[{required: true, message: '请选择费用科目'}]">
									<a-select
										v-model:value="feeSubjectId[index]"
										mode="multiple"
										style="width: 100%"
										:options="dict.otherDictList"
										size="middle"
										:field-names="{label: 'name', value: 'id', options: 'metaList'}"
										placeholder="请选择费用科目"
										@blur="selectFee(index)"
										@focus="autofocus(index)"></a-select>
								</a-form-item>
							</a-col>
						</a-row>
						<a-row :gutter="24">
							<a-col :span="8">
								<a-form-item label="企业名称:" htmlFor="label" :rules="[{required: true, message: '请选择企业名称'}]">
									<a-select
										v-model:value="item.invOrgId"
										size="middle"
										style="width: 100%"
										:options="enterpriseList"
										:field-names="{label: 'name', value: 'id'}"
										placeholder="请选择企业"
										@change="changeEnterprise(item.invOrgId, index, item)"
										@blur="selectEnterprise(item.invOrgId, index)"
										@focus="enterpriseFocus(item.invOrgId)"></a-select>
								</a-form-item>
							</a-col>
							<a-col :span="8">
								<a-form-item label="税号:" htmlFor="label" :rules="[{required: true, message: '请输入税号'}]">
									<a-input v-model:value="item.taxpayerNum" disabled placeholder="根据所选企业自动填充" />
								</a-form-item>
							</a-col>
							<a-col :span="8">
								<a-form-item
									label="开票设备类型:"
									htmlFor="label"
									:rules="[{required: true, message: '请选择开票设备类型'}]">
									<a-select
										v-model:value="item.deviceType"
										max-tag-count="responsive"
										mode="multiple"
										style="width: 100%"
										:options="enterPriseData[enterpriseIndex]?.taxControlDeviceTypeList"
										:field-names="{label: 'name', value: 'id'}"
										placeholder="请选择开票设备类型"></a-select>
								</a-form-item>
							</a-col>
						</a-row>
						<a-row :gutter="24">
							<a-col :span="8">
								<a-form-item label="开票人姓名:" htmlFor="label" :rules="[{required: true, message: '请输入开票人姓名'}]">
									<a-input v-model:value="item.drawerName" :maxlength="16" placeholder="请输入开票人姓名" />
								</a-form-item>
							</a-col>
							<a-col :span="8">
								<a-form-item label="复核人姓名:" htmlFor="label" :rules="[{required: true, message: '请输入复核人姓名'}]">
									<a-input v-model:value="item.reviewerName" :maxlength="16" placeholder="请输入复核人姓名" />
								</a-form-item>
							</a-col>
							<a-col :span="8">
								<a-form-item label="收款人姓名:" htmlFor="label" :rules="[{required: true, message: '请输入收款人姓名'}]">
									<a-input v-model:value="item.takerName" :maxlength="20" placeholder="请输入收款人姓名" />
								</a-form-item>
							</a-col>
						</a-row>
						<a-row :gutter="24">
							<a-col :span="8">
								<a-form-item label="地址:" htmlFor="label" :rules="[{required: true, message: '请输入地址'}]">
									<a-input v-model:value="item.sellerAddress" :maxlength="100" placeholder="请输入地址" />
								</a-form-item>
							</a-col>
							<a-col :span="8">
								<a-form-item label="电话:" htmlFor="label" :rules="[{required: true, message: '请输入电话'}]">
									<a-input v-model:value="item.sellerTel" :maxlength="20" placeholder="请输入电话" />
								</a-form-item>
							</a-col>
							<a-col :span="8">
								<a-form-item label="开户行:" htmlFor="label" :rules="[{required: true, message: '请输入开户行'}]">
									<a-input v-model:value="item.sellerBankName" :maxlength="100" placeholder="请输入开户行" />
								</a-form-item>
							</a-col>
							<a-col :span="8">
								<a-form-item label="银行卡号:" htmlFor="label" :rules="[{required: true, message: '请输入银行卡号'}]">
									<a-input v-model:value="item.sellerBankAccount" :maxlength="50" placeholder="请输入银行卡号" />
								</a-form-item>
							</a-col>
						</a-row>
						<a-row :gutter="24">
							<a-col v-if="show(item.deviceType)" :span="24">
								<a-form-item htmlFor="label">
									<template #label>
										<span v-color="{color: 'danger'}">*</span>
										金税盘/税控盘/税务 UKEY配置:
									</template>

									<a-row :gutter="24">
										<a-col :span="8">
											<a-form-item
												label="税盘号+终端号:"
												htmlFor="label"
												:rules="[{required: true, message: '请选择税盘号+终端号'}]">
												<a-select
													v-model:value="item.machineCodeId"
													size="middle"
													style="width: 100%"
													:options="extensionInfoList"
													:field-names="{label: 'name', value: 'id'}"
													placeholder="请先选择企业"
													@select="selectMachineCode(item.machineCodeId, -1)"></a-select>
											</a-form-item>
										</a-col>
										<a-col :span="8">
											<a-form-item label="剩余发票数量:" htmlFor="label" :rules="[{required: true, message: ''}]">
												<a-input
													v-model:value="item.invoiceSurplusNum"
													disabled
													placeholder="根据所选企业自动填充" />
											</a-form-item>
										</a-col>
										<a-col :span="8">
											<!-- :rules="[{required: true, message: '请输入单张开票限额'}]" -->
											<a-form-item label="单张开票限额:" htmlFor="label">
												<a-input-number
													v-model:value="item.invoiceLimit"
													disabled
													placeholder="请输入单张开票限额" />
											</a-form-item>
										</a-col>
									</a-row>
								</a-form-item>
							</a-col>
							<a-col v-if="item.deviceType?.includes(5)" :span="24">
								<a-form-item htmlFor="label">
									<template #label>
										<span v-color="{color: 'danger'}">*</span>
										全电发票配置:
									</template>
									<a-row :gutter="24">
										<a-col :span="8">
											<a-form-item
												label="主体是否存在不动产租赁服务相关的税收分类编码"
												htmlFor="label"
												:rules="[{required: true, message: ''}]">
												<a-select
													v-model:value="item.existImmovables"
													size="middle"
													style="width: 100%"
													:options="isCrossCity"
													:field-names="{label: 'name', value: 'id'}"
													placeholder=""></a-select>
											</a-form-item>
										</a-col>
										<a-col v-if="item.existImmovables" :span="8">
											<!-- :name="['otherExpenses', index, 'region']"  -->
											<a-form-item
												:rules="[{required: true, message: '请输入不动产所在省市(县)区'}]"
												htmlFor="label"
												label="不动产所在地:">
												<a-input
													:maxlength="50"
													v-model:value="item.region"
													placeholder="请输入不动产所在省市(县)区" />
											</a-form-item>
										</a-col>
										<a-col v-if="item.existImmovables" :span="8">
											<a-form-item
												label="不动产详细地址:"
												htmlFor="label"
												:rules="[{required: true, message: '请输入不动产所在详细地址'}]">
												<a-input
													:maxlength="100"
													v-model:value="item.detailedAddress"
													placeholder="请输入不动产所在详细地址" />
											</a-form-item>
										</a-col>
										<a-col v-if="item.existImmovables" :span="8">
											<a-form-item
												label="面积单位:"
												htmlFor="label"
												:rules="[{required: true, message: '请选择面积单位'}]">
												<a-select
													v-model:value="item.areaUnit"
													size="middle"
													style="width: 100%"
													:options="areaUnitList"
													:field-names="{label: 'name', value: 'id'}"
													placeholder="请选择面积单位"></a-select>
											</a-form-item>
										</a-col>
										<a-col v-if="item.existImmovables" :span="8" style="line-height: 87px">
											<a-form-item label="是否跨地(市):" htmlFor="label" :rules="[{required: true, message: ''}]">
												<a-select
													v-model:value="item.crossCitySign"
													size="middle"
													style="width: 100%"
													:options="isCrossCity"
													:field-names="{label: 'name', value: 'id'}"></a-select>
											</a-form-item>
										</a-col>
										<a-col v-if="item.existImmovables" :span="8">
											<a-form-item label="租赁起止日:" htmlFor="label" :rules="[{required: true, message: ''}]">
												<a-range-picker
													:value="[item.leaseBeginDate, item.leaseEndDate]"
													:value-format="DATE_FORMAT.DATE"
													style="flex: 1"
													@change="dates => onDateChange(item, dates)" />
											</a-form-item>
										</a-col>
										<a-col v-if="item.existImmovables" name="titleNo" :span="8">
											<a-form-item label="产权证书/不动产权号:">
												<a-input
													:maxlength="40"
													v-model:value="item.titleNo"
													placeholder="请输入产权证书/不动产权号" />
											</a-form-item>
										</a-col>
									</a-row>
								</a-form-item>
							</a-col>
						</a-row>
					</div>
				</div>
			</template>
			<!-- </div> -->
		</a-form>
		<template #footer>
			<a-button type="primary" :loading="loading" :disabled="disabled" @click="sendRequest">保存</a-button>
		</template>
	</a-modal>
</template>
<script setup lang="ts">
	import {reactive, ref, watch, defineComponent, nextTick} from 'vue'
	import {message, Empty} from 'ant-design-vue'
	import {CloseOutlined, PlusCircleOutlined, ExclamationCircleFilled} from '@ant-design/icons-vue'
	import {certRules, sealUrlRules, invoicingInfo} from '@/rules/invoice-administration'
	import {
		departmentConfigAdd,
		orgInfoAvailableList,
		listDict,
		departmentConfigUpdate,
		departmentListStore,
		spiExtensionInfo,
		invoiceMaxValue,
		departmentConfigDetails,
		orgInfoId,
		getDepartmentId
	} from '@/api/invoice-administration'
	import type {TreeSelectProps} from 'ant-design-vue'
	import {
		getOrderIndex,
		orgItemInfo,
		equipmentData,
		invoiceInfo,
		equipmentList,
		areaUnitList,
		isCrossCity
	} from '@/utils/invoice-administration'
	import XEUtils from 'xe-utils'
	import DATE_FORMAT, {nowDate} from 'yuxin-base/src/utils/date'

	const modelRef = reactive<invoiceInfo>({
		departmentId: null,
		disabledFeeSubjectId: [],
		disabledFeeSubjectIds: [],
		orgItemList: [],
		// 开票设备类型:
		deviceType: [],
		// 主体是否存在不动产租赁服务相关的税收分类编码
		existImmovables: 1,
		// 不动产所在地:省 市
		region: null,
		// 不动产详细地址
		detailedAddress: null,
		// 面积单位
		areaUnit: null,
		// 是否跨地(市)标志
		crossCitySign: 0,
		// 租赁开始日期
		leaseBeginDate: null,
		// 租赁结束日期
		leaseEndDate: null,
		// 产权证书/不动产权号
		titleNo: null
	})
	const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE
	const feeSubjectId = ref<any>([])
	const orgItem = reactive({
		feeSubjectId: [],
		feeSubjectIds: [],
		id: null,
		invOrgId: null,
		isDefault: false,
		//税号
		taxpayerNum: null,
		//税盘号
		machineCodeId: null,
		extensionNum: null,
		//剩余发票数量
		invoiceNum: null,
		//单张发票限额
		invoiceLimit: null,
		machineCode: null,
		drawerName: null,
		reviewerName: null,
		takerName: null,

		sellerAddress: null,
		sellerTel: null,
		sellerBankName: null,
		sellerBankAccount: null
	})
	const defaultFee = ref<any>({})
	const otherExpenses = ref<any>([])
	const modelRules = ref<any>([])
	// 企业开票设备类型
	const enterPriseData = ref<any>([])
	const imgList = reactive([])
	const props = defineProps<{
		detail: object
		visible: boolean
	}>()

	const formRules = {
		...certRules
	}
	const enterpriseIndex = ref(0)
	const loading = ref<boolean>(false)
	const disabled = ref(false)
	//添加特殊费用
	const listPush = () => {
		let info = XEUtils.clone(orgItem, true)

		let data = {
			deviceType: [],
			// 主体是否存在不动产租赁服务相关的税收分类编码
			existImmovables: 1,
			// 不动产所在地:省 市
			region: null,
			// 不动产详细地址
			detailedAddress: null,
			// 面积单位
			areaUnit: null,
			// 是否跨地(市)标志
			crossCitySign: 0,
			// 租赁开始日期
			leaseBeginDate: null,
			// 租赁结束日期
			leaseEndDate: null,
			// 产权证书/不动产权号
			titleNo: null
		}
		info = {
			...info,
			...data
		}

		if (otherExpenses.value.length < 10) {
			otherExpenses.value.push(info)
			disabledFeeSubjectIdChange()
		}
	}
	const oldIndex = ref(-2)

	const disabledFeeSubjectIdChange = (type = -1) => {
		let list = (modelRef.disabledFeeSubjectId || []).filter(o => o === -1)
		let dictList = XEUtils.clone(dict.otherDictList.length ? dict.otherDictList : dict.dictList, true)
		if (list.length && dict.otherDictList.length === 0) {
			dict.otherDictList = dictList
		} else {
			let disabledFeeSubjectId = modelRef.disabledFeeSubjectId.concat(feeSubjectId.value.flat())
			dictList.forEach(item => {
				item.metaList.forEach(o => {
					if (disabledFeeSubjectId.includes(o.id)) {
						o.disabled = true
					} else {
						o.disabled = false
					}
				})
			})
			if (type !== -1) {
				console.log(dict.notInvoiced, 'dict.notInvoiced')
				dict.notInvoiced.forEach(item => {
					item?.metaList &&
						item.metaList.forEach(o => {
							if (disabledFeeSubjectId.includes(o.id)) {
								o.disabled = true
							} else {
								o.disabled = false
							}
						})
				})
			}

			dict.otherDictList = dictList
		}
		if (type !== -1) {
			let feeSubjectIdInfo: any = []
			if (feeSubjectId.value[type] && feeSubjectId.value[type].length) {
				let toTreeArray: any = XEUtils.toTreeArray(dict.dictList).map((o: any) => o.metaList) as []
				let filterList = (toTreeArray.flat() || []).filter((o: any) => feeSubjectId.value[type].includes(o.id))
				filterList.length && filterList.forEach(o => feeSubjectIdInfo.push({id: o.id, name: o.name}))
			}
			otherExpenses.value[type].feeSubjectIds = feeSubjectIdInfo
		}
		oldIndex.value = type
	}
	//删除费用
	const listDetele = (index: number) => {
		autofocus(index)
		enterpriseFocus(otherExpenses.value[index].invOrgId)
		otherExpenses.value.splice(index, 1)
		feeSubjectId.value.splice(index, 1)
		disabledFeeSubjectIdChange()
	}
	//获取已选择部门
	const selectedDepId = ref<any>([])
	const getDepartmentIdList = () => {
		getDepartmentId({isDefault: true}).then(res => {
			console.log('res.data:', res.data)
			selectedDepId.value = res.data.map(o => o.departmentId)
		})
	}
	//获取部门列表
	const treeData = ref<any[]>([])
	const treeExpandedKeys = ref<any[]>([])
	const getDepartmentListStore = () => {
		departmentListStore().then(({data}) => {
			treeData.value[0] = data
			treeExpandedKeys.value[0] = treeData.value[0].id
			let timeOut = setTimeout(() => {
				queryTree(treeData.value, selectedDepId.value)
				clearTimeout(timeOut)
			}, 200)
		})
	}
	//部门树禁用
	const queryTree = (tree, list) => {
		let stark = []
		stark = stark.concat(tree)
		while (stark.length) {
			const temp: any = stark.shift()
			if (temp.childList) {
				stark = stark.concat(temp.childList, list)
			}
			if (list.includes(temp.id)) {
				temp.disabled = true
			}
		}
	}
	const select = (e: any) => {
		modelRef.departmentId = e
		getEnterpriseList()
	}
	//企业列表
	const enterpriseList = ref<any>([])
	// 查询可用企业
	const getEnterpriseList = () => {
		let obj = {
			size: 100,
			status: 3,
			departmentId: modelRef.departmentId
		}
		orgInfoAvailableList(obj).then(res => {
			if (!res.data.length) {
				return message.warning('当前无可用的开票主体，请先配置开票主体')
			}
			console.log(res.data, 'data')
			enterpriseList.value = res.data
			enterPriseData.value = res.data

			enterPriseData.value = enterPriseData.value.map((o: any) => {
				let taxControlDeviceTypeList: any = []
				o.taxControlDeviceTypes?.forEach((e: any) => {
					taxControlDeviceTypeList.push({
						name: equipmentData[Number(e)],
						id: Number(e)
					})
				})
				return {
					...o,
					taxControlDeviceTypeList
				}
			})
			// (data: any[]) => (data.value = d)
		})
	}
	//选择企业
	const selectEnterpriseList = ref<any[]>([])
	//主体注册类型 1 接口， 2平台绑定
	const sourceType = ref<number>(0)
	//根据id查询企业主体信息
	const getOrgInfoId = (id: string, type: number) => {
		if (!id) return
		orgInfoId(id).then(res => {
			// setForm(ref.data)
			let list: any = []
			console.log(res.data?.machineInfos && res.data.machineInfos.length && res.data.sourceType == 2, '222')
			if (res.data?.machineInfos && res.data.machineInfos.length && res.data.sourceType == 2) {
				for (let item of res.data.machineInfos) {
					if (type === -1) {
						list = [
							{
								name: item.machineCode + ' + ' + item.extensionNum,
								id: item.machineCode + ' + ' + item.extensionNum,
								machineCode: item.machineCode,
								extensionNum: item.extensionNum,
								invoiceSurplusNum: item?.invoiceSurplusNum || null,
								invoiceMaxValue: item?.invoiceMaxValue || null
							}
						]
					} else {
						list.push({
							name: item.machineCode + ' + ' + item.extensionNum,
							id: item.machineCode + ' + ' + item.extensionNum,
							machineCode: item.machineCode,
							extensionNum: item.extensionNum,
							invoiceSurplusNum: item?.invoiceSurplusNum || null,
							invoiceMaxValue: item?.invoiceMaxValue || null
						})
					}
				}
				setValue(list, type)
			} else {
				if (res.data.sourceType == 2) {
					list = null
					setValue(list, type)
				}
				if (type === -1) {
					defaultFee.value.machineCodeId = null
					defaultFee.value.machineCode = null
					defaultFee.value.extensionNum = null
					defaultFee.value.invoiceSurplusNum = null
					defaultFee.value.invoiceMaxValue = null
					defaultFee.value.invoiceLimit = null
				} else {
					otherExpenses.value[type].machineCodeId = null
					otherExpenses.value[type].machineCode = null
					otherExpenses.value[type].extensionNum = null
					otherExpenses.value[type].invoiceSurplusNum = null
					otherExpenses.value[type].invoiceMaxValue = null
					otherExpenses.value[type].invoiceLimit = null
				}
			}
			if (type !== -1) {
				otherExpenses.value[type].sellerAddress = res.data.enterpriseAddress || null
				otherExpenses.value[type].sellerTel = res.data.contactsPhone || null
				otherExpenses.value[type].machineCodeId = null
			} else {
				defaultFee.value.sellerAddress = res.data.enterpriseAddress || null
				defaultFee.value.sellerTel = res.data.contactsPhone || null
				defaultFee.value.machineCodeId = null
			}
			sourceType.value = res.data.sourceType
			getSpiExtensionInfo(id, type)
		})
	}
	//赋值
	const setValue = (list, type) => {
		if (type !== -1) {
			if (!extensionInfo.value.length) extensionInfo.value.push(list)
			console.log(extensionInfo.value)
			if (extensionInfo.value.length && extensionInfo.value[type] instanceof Array && extensionInfo.value[type].length)
				extensionInfo.value[type] = list
			if (extensionInfo.value.length && extensionInfo.value[type] instanceof Array && !extensionInfo.value[type].length)
				extensionInfo.value[type].push(list)
		} else {
			extensionInfoList.value = list
		}
	}
	const selectEnterprise = (id: string, type: number) => {
		console.log(type, 'tupe')
		let index = enterpriseList.value.findIndex(o => o.id === id)
		if (type === -1) {
			defaultFee.value.taxpayerNum = enterpriseList.value[index]?.taxpayerNum || ''
		} else if (index !== -1) {
			otherExpenses.value[type].taxpayerNum = enterpriseList.value[index]?.taxpayerNum
		}
		if (index !== -1 && enterpriseList.value[index]) {
			enterpriseList.value[index].disabled = true
		}
		selectEnterpriseList.value.push(enterpriseList.value[index])

		getOrgInfoId(id, type)
	}
	//获取费用科目
	const selectFee = (type: number) => {
		if (type == -1) {
			let isNotHave = (modelRef.disabledFeeSubjectId || []).filter(o => o == -1)
			if (isNotHave.length) {
				modelRef.disabledFeeSubjectId = isNotHave
				dict.notInvoiced.forEach(o => {
					if (o?.metaList && o?.metaList.length) {
						o.metaList.forEach(e => {
							e.disabled = true
						})
					}
				})
			} else {
				dict.notInvoiced.forEach(o => {
					if (o?.metaList && o?.metaList.length) {
						o.metaList.forEach(e => {
							e.disabled = false
						})
					}
				})
			}
		}
		disabledFeeSubjectIdChange(type)
	}
	//费用选择取消disabled
	const autofocus = index => {
		//-1为不可选费用列表
		let disabledFeeSubjectId: any = index === -1 ? modelRef.disabledFeeSubjectId : feeSubjectId.value[index] || []
		let arr: any = index == -1 ? dict.notInvoiced : dict.otherDictList
		if (disabledFeeSubjectId.length) {
			arr.forEach(item => {
				item?.metaList &&
					item.metaList.forEach(o => {
						if (disabledFeeSubjectId.includes(o.id)) {
							o.disabled = false
						}
					})
			})
		}
	}
	//企业选择取消disabled
	const enterpriseFocus = invOrgId => {
		if (invOrgId) {
			let index = enterpriseList.value.findIndex(o => o.id === invOrgId)
			if (index !== -1 && Object.hasOwn(enterpriseList.value[index], 'disabled')) {
				enterpriseList.value[index].disabled = false
			}
		}
	}

	const dict = reactive<any>({
		//默认费用
		dictList: [],
		//不开票费用
		notInvoiced: [],
		//其他特殊费用
		otherDictList: []
	})

	const getDictList = () => {
		listDict().then(res => {
			console.log(res.data)
			dict.dictList = res.data
			dict.notInvoiced = XEUtils.clone(res.data, true)
			dict.notInvoiced.unshift({id: -1, name: '无'})
			console.log('dict.notInvoiced:', dict.notInvoiced)
		})
	}
	//获取税盘号+终端号
	const extensionInfoList = ref<any[]>([])
	const extensionInfo = ref<any>([])
	const getSpiExtensionInfo = (id: string, type: number) => {
		spiExtensionInfo(id).then(res => {
			console.log(res.data)
			let list: any = []
			for (let item of res.data) {
				if (type === -1) {
					list = [
						{
							name: item.machineCode + ' + ' + item.extensionNum,
							id: item.machineCode + ' + ' + item.extensionNum,
							machineCode: item.machineCode,
							invoiceSurplusNum: item?.invoiceSurplusNum || null,
							extensionNum: item.extensionNum,
							invoiceMaxValue: item?.invoiceMaxValue || null
						}
					]
				} else {
					list.push({
						name: item.machineCode + ' + ' + item.extensionNum,
						id: item.machineCode + ' + ' + item.extensionNum,
						invoiceSurplusNum: item?.invoiceSurplusNum || null,
						machineCode: item.machineCode,
						extensionNum: item.extensionNum,
						invoiceMaxValue: item?.invoiceMaxValue || ''
					})
				}
			}
			setValue(list, type)
			let id = type === -1 ? list[0]?.id : list[list.length - 1]?.id
			let timeOut = setTimeout(() => {
				id && selectMachineCode(id, type)
				clearTimeout(timeOut)
			}, 100)
		})
	}
	//选择税号
	const selectMachineCode = (id: string, type: number) => {
		let index = -1,
			info = {}
		if (type === -1) {
			index = extensionInfoList.value.findIndex(o => o.id === id)
			if (index === -1) return
			defaultFee.value.machineCode = extensionInfoList.value[index].machineCode
			defaultFee.value.extensionNum = extensionInfoList.value[index].extensionNum
			defaultFee.value.machineCodeId = extensionInfoList.value[index].machineCode + '+' + extensionInfoList.value[index].extensionNum
			defaultFee.value.invoiceSurplusNum = extensionInfoList.value[index].invoiceSurplusNum
			sourceType.value == 2 && (defaultFee.value.invoiceLimit = extensionInfoList.value[index].invoiceMaxValue)
			info = {
				extensionNum: defaultFee.value.extensionNum,
				machineCode: defaultFee.value.machineCode,
				orgId: defaultFee.value.invOrgId
			}
		} else {
			index = extensionInfo.value[type] ? extensionInfo.value[type].findIndex(o => o.id === id) : -1
			if (index === -1) return
			otherExpenses.value[type].machineCode = extensionInfo.value[type][index].machineCode
			otherExpenses.value[type].extensionNum = extensionInfo.value[type][index].extensionNum
			otherExpenses.value[type].invoiceSurplusNum = extensionInfo.value[type][index].invoiceSurplusNum
			otherExpenses.value[type].machineCodeId =
				extensionInfo.value[type][index].machineCode + '+' + extensionInfo.value[type][index].extensionNum
			sourceType.value == 2 && (otherExpenses.value[type].invoiceLimit = extensionInfo.value[type][index].invoiceMaxValue)
			info = {
				extensionNum: otherExpenses.value[type].extensionNum,
				machineCode: extensionInfo.value[type][index].machineCode,
				orgId: otherExpenses.value[type].invOrgId
			}
		}
		sourceType.value == 1 && getInvoiceMaxValue(info, type)
	}
	//获取发票限额
	const getInvoiceMaxValue = (info: object, type: number) => {
		invoiceMaxValue(info).then(res => {
			if (type === -1) {
				defaultFee.value.invoiceLimit = res.data
			} else {
				otherExpenses.value[type].invoiceLimit = res.data
			}
		})
	}
	//提交
	const sendRequest = () => {
		if (!modelRef.departmentId) {
			return message.error('请选择部门')
		}
		if (!modelRef.disabledFeeSubjectId.length) {
			return message.error('请选择不可开票科目')
		}
		let data = {
			// 开票设备类型:
			deviceType: modelRef.deviceType,
			// 主体是否存在不动产租赁服务相关的税收分类编码
			existImmovables: modelRef.existImmovables,
			// 不动产所在地:省 市
			region: modelRef.region,
			// 不动产详细地址
			detailedAddress: modelRef.detailedAddress,
			// 面积单位
			areaUnit: modelRef.areaUnit,
			// 是否跨地(市)标志
			crossCitySign: modelRef.crossCitySign,
			// 租赁开始日期
			leaseBeginDate: modelRef.leaseBeginDate,
			// 租赁结束日期
			leaseEndDate: modelRef.leaseEndDate,
			// 产权证书/不动产权号
			titleNo: modelRef.titleNo
		}
		defaultFee.value = {
			...defaultFee.value,
			...data
		}
		if (otherExpenses.value && otherExpenses.value.length) {
			modelRef.orgItemList = [...otherExpenses.value]
			modelRef.orgItemList.unshift(defaultFee.value)
		} else {
			modelRef.orgItemList = [...[defaultFee.value]]
		}
		if (!check(modelRef.orgItemList)) return
		formRef.value.validate().then(() => {
			modelRef.orgItemList[0].feeSubjectIds = []
			//过滤不可选费用科目
			let disabledFeeSubjectIds: any = []
			if (!modelRef.disabledFeeSubjectId.includes(-1)) {
				let notInvoiced = XEUtils.toTreeArray(dict.dictList).map((o: any) => o.metaList) as []
				let disabledFeeSubject: any = (notInvoiced.flat() || []).filter((o: any) => modelRef.disabledFeeSubjectId.includes(o.id))
				disabledFeeSubject.length && disabledFeeSubject.map(o => disabledFeeSubjectIds.push({id: o.id, name: o.name}))
			}
			let info = {
				departmentId: modelRef.departmentId,
				disabledFeeSubjectIds: disabledFeeSubjectIds,
				orgItemList: modelRef.orgItemList
			}

			loading.value = true
			let fun: any = props.detail?.departmentId ? departmentConfigUpdate : departmentConfigAdd
			// return
			fun(info)
				.then(({data}) => {
					message.success('开票信息保存成功，请前往下一步，配置税收信息')
					emit('success')
					cancel()
				})
				.finally(() => (loading.value = false))
		})
	}
	const check = list => {
		let keyList = [
			'invOrgName',
			'deptId',
			'sourceType',
			'feeSubjectId',
			'feeSubjectIds',
			'id',
			'isDefault',
			'extensionNum',
			'machineCode',
			'invoiceMaxValue',
			'invoiceNum',
			'invoiceLimit',
			'invoiceSurplusNum',
			'crossCitySign',
			'existImmovables',
			'titleNo'
		]
		let keyDataLits = [
			'invOrgName',
			'deptId',
			'sourceType',
			'feeSubjectId',
			'feeSubjectIds',
			'id',
			'isDefault',
			'extensionNum',
			'machineCode',
			'invoiceMaxValue',
			'invoiceNum',
			'invoiceLimit',
			'invoiceSurplusNum',
			'crossCitySign',
			'titleNo',
			'leaseBeginDate',
			'leaseEndDate',
			'region',
			'detailedAddress',
			'areaUnit',
			'existImmovables',
			'machineCodeId'
		]

		// 	'titleNo'
		if (list.some((e: any) => e.deviceType?.length == 0)) {
			message.error('请选择开票设置类型')
			return false
		} else {
			for (let i in list) {
				if ((!list[i]?.deviceType.includes(5) && show(list[i]?.deviceType)) || !list[i].existImmovables) {
					console.log('执行了吗')
					//这里判断是不是需要
					for (let key in list[i]) {
						if (list[i] && !list[i][key] && !keyDataLits.includes(key)) {
							// Array.isArray()
							message.error(invoicingInfo[key] || '')
							return false
						} else if (list[i] && key === 'feeSubjectIds' && !list[i][key] && i != 0) {
							message.error(invoicingInfo[key])
							return false
						}
					}
				} else {
					for (let key in list[i]) {
						if (list[i] && !list[i][key] && !keyList.includes(key)) {
							message.error(invoicingInfo[key] || '')
							return false
						} else if (list[i] && key === 'feeSubjectIds' && !list[i][key] && i != 0) {
							message.error(invoicingInfo[key])
							return false
						} else if (list[i] && key === 'region' && list[i][key]?.length < 4) {
							message.error('不动产所在地,请输入4-50个字符')
							return false
						}
					}
				}
			}
			return true
		}
	}
	const formRef = ref<any>()

	const emit = defineEmits(['update:visible', 'success'])
	const cancel = () => {
		otherExpenses.value = []
		feeSubjectId.value = []
		dict.otherDictList = []
		extensionInfoList.value = []
		extensionInfo.value = []
		enterpriseList.value = []
		selectedDepId.value = []
		Object.keys(modelRef).forEach(key => {
			modelRef[key] = null
		})
		modelRef.disabledFeeSubjectId = []
		modelRef.disabledFeeSubjectIds = []
		modelRef.orgItemList = []
		modelRef.deviceType = []
		modelRef.existImmovables = 1
		modelRef.region = null
		modelRef.detailedAddress = null
		modelRef.areaUnit = null
		modelRef.crossCitySign = 0
		modelRef.leaseBeginDate = null
		modelRef.leaseEndDate = null
		modelRef.titleNo = null

		emit('update:visible', false)
	}
	//驳回原因
	const rejectionReason = ref('')
	//编辑查询详情
	const getDetailedInfo = () => {
		departmentConfigDetails(props.detail.departmentId).then(res => {
			console.log(res.data, 'res1111')
			rejectionReason.value = XEUtils.clone(res.data?.rejectionReason, true) || ''
			modelRef.departmentId = XEUtils.clone(res.data.departmentId, true)
			modelRef.disabledFeeSubjectId = []
			res.data.disabledFeeSubjectIds.forEach(o => modelRef.disabledFeeSubjectId.push(o.id))
			let orgItemList = XEUtils.clone(res.data.orgItemList, true)
			!modelRef.disabledFeeSubjectId.length && modelRef.disabledFeeSubjectId.push(-1)

			console.log(orgItemList, 'orgItemList')

			for (let i = 0; i < res.data.orgItemList.length; i++) {
				if (i === 0) {
					defaultFee.value = res.data.orgItemList[0]
					for (let key in res.data.orgItemList[0]) {
						if (modelRef.hasOwnProperty(key)) {
							modelRef[key] = res.data.orgItemList[0][key]
						}
					}
					modelRef.existImmovables = modelRef.existImmovables ? 1 : 0
					modelRef.crossCitySign = modelRef.crossCitySign ? 1 : 0

					let times = setTimeout(() => {
						selectEnterprise(defaultFee.value.invOrgId, -1)
						clearTimeout(times)
					}, 200)
					let time = setTimeout(() => {
						selectMachineCode(defaultFee.value.machineCode, -1)
						clearTimeout(time)
					}, 1200)
				} else {
					listPush()
					otherExpenses.value[i - 1] = orgItemList[i]
					otherExpenses.value[i - 1].existImmovables = otherExpenses.value[i - 1].existImmovables ? 1 : 0
					otherExpenses.value[i - 1].crossCitySign = otherExpenses.value[i - 1].existImmovables ? 1 : 0
					let list: any = (orgItemList[i]?.feeSubjectIds || []).map((o: any) => {
						return o.id
					})
					otherExpenses.value[i - 1].feeSubjectIds = list
					feeSubjectId.value[i - 1] = list
					selectFee(i - 1)
					let times = setTimeout(() => {
						selectEnterprise(orgItemList[i]?.invOrgId, i - 1)
						clearTimeout(times)
					}, 200)
					let time = setTimeout(() => {
						selectMachineCode(orgItemList[i]?.machineCode, i - 1)
						clearTimeout(time)
					}, 1200)
				}
			}
		})
	}

	watch(
		() => props.visible,
		(newVal, oldVal) => {
			selectEnterpriseList.value = []
			if (newVal) {
				defaultFee.value = {...orgItem}
				defaultFee.value.isDefault = true
				modelRules.value = certRules
				getDepartmentIdList()
				getDictList()
				getDepartmentListStore()
				if (props.detail.hasOwnProperty('departmentId')) {
					getDetailedInfo()
					getEnterpriseList()
				}
			}
		}
	)

	const onDateChange = (item, dates: string[]) => {
		if (dates?.length) {
			item.leaseBeginDate = dates[0]
			item.leaseEndDate = dates[1]
		}
	}

	const changeEnterprise = (id: string, index: number, data) => {
		if (index === -1) {
			modelRef.deviceType = []
		} else {
			data.deviceType = []
		}

		enterpriseIndex.value = enterPriseData.value?.findIndex((e: any) => e.id === id)
	}

	//是否展示
	const show = (data: any) => {
		if (data?.includes(1) || data?.includes(2)) {
			return true
		}
		return false
	}
</script>
<style lang="less">
	.add-invoicing-info {
		overflow-y: auto;
		padding: 24px;
		.url-input {
			position: absolute;
			width: 125px;
			height: 128px;
			z-index: -1;
			top: 0;
			left: 0;
		}
		.text {
			font-size: 12px;
			color: #999;
		}
		.ant-form-vertical .display-flex {
			flex-direction: initial;
			.ant-form-item-control-input-content {
				margin: -8px 0 0 10px;
			}
		}
		.code {
			display: inline-block;
			margin-right: 10px;
		}
		.tip-info {
			width: 100%;
			height: 40px;
			line-height: 40px;
			background: #fffbe6;
			border-radius: 2px 2px 2px 2px;
			opacity: 1;
			border: 1px solid #ffe58f;
			font-size: 14px;
			margin-bottom: 20px;
			padding-left: 16px;
		}

		.special-expenses-box {
			width: 100%;
			// height: 480px;
			border-radius: 2px 2px 2px 2px;
			opacity: 1;
			border: 1px solid #d6e6ff;
			margin: 10px auto;
			.title {
				width: 100%;
				padding-left: 10px;
				display: flex;
				flex-wrap: wrap;
				align-content: center;
				justify-content: space-between;
				height: 46px;
				background: #f6f9fc;
				border-radius: 2px 2px 0px 0px;
				font-size: 14px;
				font-weight: 500;
				color: #0266ff;
				line-height: 46px;
				.ant-btn-link {
					line-height: 35px;
				}
			}
			.form-main {
				padding: 10px;
			}
		}
		.list-null {
			width: 100%;
			height: 134px;
			border-radius: 2px 2px 2px 2px;
			opacity: 1;
			border: 1px solid rgba(0, 0, 0, 0.15);
			margin: 10px auto;
		}
		.fee-title {
			margin: 0 0 10px;
			.anticon-plus-circle {
				color: #0266ff;
			}
		}
	}
</style>
